// @flow
import React from 'react'
import { Radio, message } from 'antd'
import MalfunctionLine from 'components/MalfunctionLine'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import styles from './Condition.css'
import MalfunctionGrid from 'components/MalfunctionGrid'
import { connect } from 'react-redux'
// import R from 'ramda'
import moment from 'moment'
type Props = {
  history: Object,
  deviceId: number
}
type States = {
  allData: Array<Object>,
  gridData: Array<Object>,
  xData: Array<any>,
  chartData: Array<any>,
  startTime: any,
  endTime: any
}
const RadioGroup = Radio.Group
class Condition extends React.Component {
  props: Props
  state: States
  constructor (props: Props) {
    super(props)
    this.state = {
      allData: [],
      gridData: [],
      startTime: '',
      endTime: '',
      xData: [],
      chartData: []
    }
  }
  // componentWillReceiveProps (nextProps) {
  //   if (!R.equals(nextProps, this.props)) {
  //     this.getAllData(nextProps)
  //   }
  // }
  componentWillMount () {
    this.getAllData(this.props)
  }
  componentDidMount () {
    const { deviceId } = this.props
    const component = this
    // 故障表格
    universalFetch(`${__SERVICE_API__}device/devices/${deviceId}/events?types=fault&&orderBy=start_time desc`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        component.setState({
          gridData: json.result.eventList.map((d, i) => {
            d['startTime'] = moment(d.startTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
            d['endTime'] = moment(d.endTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
            return d
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getAllData (props) {
    // const { deviceId } = props
    // 获取所有的总值
    universalFetch(`${__SERVICE_API__}device/events1/faults/types/count`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        this.setState({
          allData: result
        }, () => {
          // 故障柱状图
          this.draw()
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  draw () {
    const { deviceId } = this.props
    let { startTime, endTime, allData } = this.state
    const component = this
    if (startTime) {
      startTime = startTime.toISOString()
    }
    if (endTime) {
      endTime = endTime.toISOString()
    }
    universalFetch(`${__SERVICE_API__}device/events1/faults/types/count?deviceId=${deviceId}` +
      `&startDate=${startTime}&endDate=${endTime}&type=fault`
    )
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const result = json.result
        if (result === '') {
          component.setState({
            xData: [],
            chartData: []
          })
          message.info('暂无数据')
        } else {
          const xData = json.result.map((d, i) => {
            return d.eventType
          })
          component.setState({
            xData: xData,
            chartData: [{
              name: '故障频次',
              type: 'column',
              animation: true,
              data: json.result.map((d, i) => {
                return d.count
              })
            }, {
              name: '故障总数',
              type: 'column',
              animation: true,
              data: allData.filter((dd) => xData.indexOf(dd.eventType) !== -1).map((d, i) => {
                return d.count
              })
            }]
          })
        }
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  onChange = (e: Object) => {
    const value = e.target.value
    let now = moment()
    if (value === 'week') {
      this.setState({
        startTime: moment().subtract(7, 'days'),
        endTime: now
      }, () => {
        this.draw()
      })
    } else if (value === 1) {
      this.setState({
        startTime: moment().subtract(1, 'months'),
        endTime: now
      }, () => {
        this.draw()
      })
    } else if (value === 3) {
      this.setState({
        startTime: moment().subtract(3, 'months'),
        endTime: now
      }, () => {
        this.draw()
      })
    } else if (value === 6) {
      this.setState({
        startTime: moment().subtract(6, 'months'),
        endTime: now
      }, () => {
        this.draw()
      })
    } else if (value === 12) {
      this.setState({
        startTime: moment().subtract(1, 'years'),
        endTime: now
      }, () => {
        this.draw()
      })
    } else if (value === 'all') {
      this.setState({
        startTime: '',
        endTime: ''
      }, () => {
        this.draw()
      })
    }
  }
  render () {
    const { history } = this.props
    const { gridData, xData, chartData, allData } = this.state
    return (
      <div className={styles['main']}>
        <div className={styles['condition']}>
          <RadioGroup onChange={this.onChange} defaultValue={'all'}>
            <Radio value={'week'}>近一周</Radio>
            <Radio value={1}>近一月</Radio>
            <Radio value={3}>近三月</Radio>
            <Radio value={6}>近半年</Radio>
            <Radio value={12}>近一年</Radio>
            <Radio value={'all'}>全部</Radio>
          </RadioGroup>
        </div>
        <div className={styles['top']}>
          <MalfunctionLine xData={xData} chartData={chartData} chartAllData={allData} />
        </div>
        <MalfunctionGrid {...{
          history,
          rowData: gridData
        }} />
      </div>
    )
  }
}
const mapStatesToProps = (state) => {
  return {
    deviceId: state.deviceCard.deviceData.id
  }
}
export default connect(mapStatesToProps, {})(Condition)
